package test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

import kj.dsp.KJDigitalSignalProcessor;

public class Visualizer extends JFrame implements KJDigitalSignalProcessor {

	int gap = 5, min = -10, max = 30;

	public Visualizer() {
		super("Visualizer");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(800, 600);
		setLocationRelativeTo(null);
		setVisible(true);
		this.createBufferStrategy(2);
	}

	public void receive(int[] data) {
		BufferStrategy bf = this.getBufferStrategy();

		Graphics g = bf.getDrawGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, getWidth(), getHeight());
		g.setColor(new Color(0, 0, 100));
		int totalGapSpace = (data.length + 1) * (gap);
		int barWidth = (getWidth() - totalGapSpace) / data.length;
		int x = 0;
		for (int i = 0; i < data.length; i++) {
			int value = data[i];
			int height = (value - min) * getHeight() / (max - min);
			x += gap;
			g.fillRect(x, getHeight() - height, barWidth, height);
			x += barWidth;
		}
		g.dispose();
		bf.show();
	}

	private float[] stereoMerge(float[] pLeft, float[] pRight) {
		for (int a = 0; a < pLeft.length; a++) {
			pLeft[a] = (pLeft[a] + pRight[a]) / 2.0f;
		}
		return pLeft;
	}

	private void drawScope(Graphics pGrp, float[] pSample) {
		int height_2 = getHeight() >> 1;
		int width = getWidth();
		Color scopeColor = Color.blue;
		pGrp.setColor(scopeColor);
		int wLas = (int) (pSample[0] * height_2) + height_2;
		int wSt = 2;
		for (int a = wSt, c = 0; c < width; a += wSt, c++) {
			int wAs = (int) (pSample[a] * height_2) + height_2;
			pGrp.drawLine(c, wLas, c + 1, wAs);
			wLas = wAs;
		}
	}

	@Override
	public void process(float[] pLeft, float[] pRight, float pFrameRateRatioHint) {
		BufferStrategy bf = this.getBufferStrategy();
		Graphics g = bf.getDrawGraphics();
		g.setColor(Color.black);
		g.fillRect(0, 0, getWidth(), getHeight());
		drawScope(g, stereoMerge(pLeft, pRight));
		g.dispose();
		bf.show();
	}
}
